package cn.sharp.bbs.service.impl;

import cn.sharp.bbs.common.Utils;
import cn.sharp.bbs.dao.gen.UserMapper;
import cn.sharp.bbs.dao.security.RegisterDao;
import cn.sharp.bbs.dao.user.UserDao;
import cn.sharp.bbs.entity.BO.RegisterEntity;
import cn.sharp.bbs.entity.DO.User;
import cn.sharp.bbs.service.RegisterService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Transactional
@Service
public class RegisterServiceImpl implements RegisterService {
    @Resource
    private RegisterDao registerDao;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserDao userDao;
    /**
     * 检查邮箱是否不重复
     * @param email 邮箱地址
     * @return 布尔值, 代表是否重复
     */
    @Override
    public boolean isNewEmail(String email) {
        return registerDao.countUserByEmail(email) == 0;
    }

    /**
     * 检查账号名是否不重复
     * @param account 账号名
     * @return 布尔值, 代表是否重复
     */
    @Override
    public boolean isNewAccount(String account) {
        return registerDao.countUserByAccount(account)==0;
    }

    @Override
    public Long doRegister(RegisterEntity registerEntity) {
        User user = new User();
        user.setNum(registerEntity.getAccount());
        user.setMail(registerEntity.getEmail());
        user.setPwd(registerEntity.getPasswd());
        user.setName(registerEntity.getAccount());
        user.setState(-1);
        userDao.insertNewUser(user);
        return user.getId();
    }

    /**
     * 检查是否可以进行注册
     * @param entity 传入的注册用实体
     * @return 不可注册时返回原因, 否则返回null
     */
    @Override
    public String checkRegistry(RegisterEntity entity) {
        if(entity.getAccount()==null||entity.getEmail()==null||entity.getPasswd()==null
                ||entity.getAccount().equals("")||entity.getEmail().equals("")
                ||entity.getPasswd().equals(""))
            return  "提供的注册信息不完整";
        if(!Utils.isValidEmail(entity.getEmail())||!Utils.isValidAccountName(entity.getAccount()))
            return "账号或邮箱格式错误";
        if(entity.getPasswd().length()>20||entity.getPasswd().length()<8)
            return "密码长度错误";
        if(!isNewAccount(entity.getAccount()))
            return "该账户名已存在";
        if(!isNewEmail(entity.getEmail()))
            return  "该邮箱已被使用";
        else
            return null;
    }
}
